<route>
{
  "meta":{
    "title":"添加用户席位",
    "localism": "sys.add_authorized_user_seat"
  }
}
</route>
<template>
  <div class="authorization" ref="card" v-loading="loading">
    <div class="authorization_appInfo tc">
      <span class="">
        {{ $t("sys.apply_name") }}：<span>{{ APP_INFO.appName }}</span>
      </span>
      <span class="ml80">
        {{ $t("sys.appUniqueId") }}：<span>{{ APP_INFO.appUniqueId }}</span>
      </span>
      <span class="ml80">
        {{ $t("sys.authorization_server_status") }}：<span
          :style="{ color: LINE_STATUS_ENUM[line_status].color }"
          >{{ $t(LINE_STATUS_ENUM[line_status].i18n) }}</span
        >
      </span>
    </div>
    <div class="authorization_warp">
      <el-form
        v-if="line_status === 'online'"
        :model="online_form"
        ref="online_form"
        label-width="150px"
      >
        <el-form-item
          :label="$t('sys.activate_code') + ' ：'"
          prop="license"
          :rules="[
            {
              required: true,
              message: $t('sys.enter_authorization_code'),
              trigger: 'change',
            },
          ]"
        >
          <el-input
            @blur="handleBlur"
            v-model="online_form.license"
            :placeholder="$t('sys.enter_authorization_code')"
          />
        </el-form-item>
        <template v-if="licenseType === 'TEST' || licenseType === 'FORMAL'">
          <el-form-item
            v-if="licenseType === 'FORMAL'"
            :label="$t('sys.dateType') + ' ：'"
            prop="dateType"
            :rules="[
              {
                required: true,
                message: $t('sys.select_dateType'),
                trigger: 'change',
              },
            ]"
          >
            <el-radio-group
              v-model="online_form.dateType"
              @change="handleChange"
            >
              <el-radio-button label="perpetual">{{
                $t("sys.perpetual")
              }}</el-radio-button>
              <el-radio-button label="date">{{
                $t("sys.date")
              }}</el-radio-button>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            v-if="licenseType === 'TEST' || online_form.dateType === 'date'"
            :label="$t('sys.expiry_date') + ' ：'"
            prop="expiryDate"
            :rules="[
              {
                required: true,
                message: $t('sys.select_expiry_date'),
                trigger: 'change',
              },
            ]"
          >
            <el-date-picker
              :clearable="false"
              style="width: 100%"
              v-model="online_form.expiryDate"
              format="yyyy-MM-dd"
              type="date"
              :placeholder="$t('sys.select_expiry_date')"
              :picker-options="{
                disabledDate: disabledDateFun,
              }"
            >
            </el-date-picker>
          </el-form-item>
        </template>
        <el-form-item class="tc mt60">
          <el-button
            class="dymBtn"
            type="primary"
            :loading="onlineActiveLoading"
            @click="onlineActivate"
            >{{ $t("sys.onlineActivate") }}</el-button
          >
        </el-form-item>
      </el-form>
      <el-form
        v-else
        :model="offline_form"
        ref="offline_form"
        label-width="150px"
      >
        <el-form-item
          :label="$t('sys.activate_code') + ' ：'"
          prop="license"
          :rules="[
            {
              required: true,
              message: $t('sys.enter_authorization_code'),
              trigger: 'change',
            },
          ]"
        >
          <el-input
            :placeholder="$t('sys.enter_authorization_code')"
            v-model="offline_form.license"
          >
            <template slot="suffix">
              <el-popover
                placement="right"
                width="160"
                trigger="manual"
                :value="!!showPop"
              >
                <div class="tc">
                  <img :src="QRcodeUrl" width="126" height="126" />
                  <div>{{ $t("sys.miniappScanQRcode") }}</div>
                </div>
                <el-button
                  slot="reference"
                  style="margin-left: 20px"
                  type="text"
                  :loading="getFileLoading"
                  @click="getQRcode"
                  >{{ $t("sys.get_authorization_file") }}</el-button
                >
              </el-popover>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item
          :label="$t('sys.authorization_file') + ' ：'"
          prop="file"
          :rules="[
            {
              required: true,
              message: $t('sys.enter_authorization_file'),
              trigger: 'change',
            },
          ]"
        >
          <Upload
            drag
            accept=".lic"
            v-model="offline_form.file"
            @input="clearValidate"
            :beforeUpload="beforeUpload"
          ></Upload>
        </el-form-item>
        <el-form-item class="tc mt60">
          <el-button
            class="dymBtn"
            @click="offlineActivate"
            type="primary"
            :loading="offlineActiveLoading"
            >{{ $t("sys.activate") }}</el-button
          >
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import {
  getLicenseIsOnline,
  getRemoteActiveInfo,
  activeAuth,
  offlineActive,
  getLicenseType,
} from "@/customApi/license.js"
import { mapGetters, mapActions } from "vuex"
import Upload from "./__components__/upload"
import QRCODE from "qrcode"
var moment = require("moment")
const LINE_STATUS_ENUM = {
  online: {
    i18n: "sys.online",
    color: "#67C23A",
  },
  offline: {
    i18n: "sys.offline",
    color: "#F56C6C",
  },
}
export default {
  name: "authorization",
  components: { Upload },
  data() {
    return {
      LINE_STATUS_ENUM,
      loading: true,
      licenseType: "TRIAL",
      online_form: {
        license: "",
        dateType: "", //perpetual=>永久 date=>日期
        expiryDate: "",
      },
      offline_form: {
        license: "",
        file: "",
      },
      onlineActiveLoading: false,
      onlineActiveDisabled: false,
      getFileLoading: false,
      offlineActiveLoading: false,
      line_status: "offline",
      offlineTimer: null,
      fileList: [],
      QRcodeUrl: "",
      dialogVisible: false,
      showPop: false,
      status: "",
    }
  },
  computed: {
    ...mapGetters(["APP_INFO", "getAuthCenterInfo"]),
  },
  created() {
    this.status = this.$route.query.status
    this.offlineTimer && clearInterval(this.offlineTimer)
    this.judgeAthu()
    this.offlineTimer = setInterval(() => {
      this.judgeAthu()
    }, 20 * 1000)
  },
  mounted() {
    this.setViewTitle({
      route: this.$route,
      title:
        this.status === "TRIAL"
          ? this.$t("sys.official_authorized")
          : this.$t("sys.add_authorized_user_seat"),
    })
  },
  destroyed() {
    this.offlineTimer && clearInterval(this.offlineTimer)
  },
  methods: {
    ...mapActions(["setViewTitle", "delVisitedViewByPath"]),
    // 获取在线状态
    judgeAthu() {
      getLicenseIsOnline()
        .then((res) => {
          this.line_status = res ? "online" : "offline"
          this.loading = false
        })
        .catch(() => {
          this.line_status = "offline"
          this.loading = false
        })
    },
    // 失焦 获取激活码类型
    async handleBlur() {
      if (!this.online_form.license) return
      this.onlineActiveDisabled = true
      try {
        let res = await getLicenseType({ license: this.online_form.license })
        this.licenseType = res
        if (!res || res === "TRIAL") {
          this.$set(this.online_form, "dateType", "")
          this.$set(this.online_form, "expiryDate", "")
          return
        } else if (res === "FORMAL") {
          this.$set(this.online_form, "dateType", "perpetual")
          this.$set(this.online_form, "expiryDate", "")
        } else {
          const year = new Date().getFullYear()
          this.$set(this.online_form, "dateType", "")
          this.$set(
            this.online_form,
            "expiryDate",
            moment(new Date(new Date().setFullYear(year + 1))).format(
              "YYYY-MM-DD"
            )
          )
        }
        this.onlineActiveDisabled = false
      } catch (error) {
        this.onlineActiveDisabled = false
      }
    },
    handleChange(v) {
      if (v === "perpetual") {
        this.$set(this.online_form, "expiryDate", "")
      } else {
        const year = new Date().getFullYear()
        this.$set(
          this.online_form,
          "expiryDate",
          moment(new Date(new Date().setFullYear(year + 1))).format(
            "YYYY-MM-DD"
          )
        )
      }
      this.$refs.online_form.validateField("expiryDate")
    },
    //禁选时间
    disabledDateFun(date) {
      if (this.licenseType === "FORMAL") {
        const allowDate = moment(new Date()).format("YYYY-MM-DD") + " 00:00:00"
        return date.getTime() < new Date(allowDate)
      } else if (this.licenseType === "TEST") {
        const year = new Date().getFullYear()
        const allowDateS = moment(new Date()).format("YYYY-MM-DD") + " 00:00:00"
        const allowDateE =
          moment(new Date(new Date().setFullYear(year + 1))).format(
            "YYYY-MM-DD"
          ) + " 23:59:59"

        return (
          date.getTime() < new Date(allowDateS) ||
          date.getTime() > new Date(allowDateE)
        )
      } else {
        return false
      }
    },
    // 获取离线激活二维码
    getQRcode() {
      this.showPop = false
      this.$refs.offline_form.validateField("license", async (errorMessage) => {
        if (errorMessage === "") {
          this.getFileLoading = true
          try {
            let res = await getRemoteActiveInfo({
              license: this.offline_form.license,
            })
            if (res) {
              let { content, url } = JSON.parse(res)
              let newData = JSON.parse(content)
              newData.seatType = "RECHARGE"
              this.QRcodeUrl = await QRCODE.toDataURL(
                JSON.stringify({
                  content: JSON.stringify(newData),
                  url,
                }),
                {
                  margin: 2,
                }
              )
              this.getFileLoading = false
              this.dialogVisible = true
              this.showPop = true
            } else {
              this.getFileLoading = false
            }
          } catch (e) {
            this.getFileLoading = false
          }
        }
      })
    },
    // 在线激活
    onlineActivate() {
      if (this.onlineActiveDisabled) return
      this.$refs.online_form.validate((valid) => {
        if (valid) {
          this.onlineActiveLoading = true
          activeAuth(this.online_form)
            .then((res) => {
              this.$message.success(this.$t("sys.operation_success"))
              this.$store.dispatch("GetLicenseInfoDto")
              if (this.status === "TRIAL") {
                this.delVisitedViewByPath(this.$route.path)
                this.$router.back()
              }
            })
            .finally(() => {
              this.onlineActiveLoading = false
            })
        }
      })
    },
    //离线激活
    offlineActivate() {
      this.$refs.offline_form.validate((valid) => {
        if (valid) {
          this.offlineActiveLoading = true
          const formData = new FormData()
          formData.append("files", this.offline_form.file)
          offlineActive(formData, {
            license: this.offline_form.license,
          })
            .then((res) => {
              this.$message.success(this.$t("sys.operation_success"))
              this.$store.dispatch("GetLicenseInfoDto")
              if (this.status === "TRIAL") {
                this.delVisitedViewByPath(this.$route.path)
                this.$router.back()
              }
            })
            .finally(() => {
              this.offlineActiveLoading = false
            })
        } else {
        }
      })
    },
    clearValidate() {
      this.$refs.offline_form.clearValidate("file")
    },
    beforeUpload(file) {
      const type = file.name.split(".").pop().toLowerCase()
      if (["lic"].includes(type)) {
        return true
      } else {
        this.$message.error("只能上传lic格式的授权文件")
        return false
      }
    },
  },
}
</script>

<style lang="scss" scoped>
.authorization {
  display: flex;
  flex-direction: column;
  height: 100%;
  min-width: 800px;
  &_appInfo {
    margin-bottom: 24px;
    background-color: rgba(237, 237, 237, 1);
    border-radius: 4px;
    line-height: 44px;
    border: 1px rgba(231, 231, 231, 1);
    .ml80 {
      margin-left: 80px;
    }
  }
  &_warp {
    flex: 1;
    display: flex;
    justify-content: center;
    align-items: center;
    .el-form {
      width: 700px;
    }
    ::v-deep .el-upload {
      width: 100%;
    }
    ::v-deep .el-upload-dragger {
      width: 100%;
    }
    .dymBtn {
      width: 176px;
    }
  }
}
</style>
